package com.xoa.controller.workflow;

import java.io.DataInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.xoa.model.users.Users;
import com.xoa.service.WFE.WFEFactory.WFEFlowProcess;
import com.xoa.service.work.WorkService;
import com.xoa.util.AjaxJson;
import com.xoa.util.CookiesUtil;
import com.xoa.util.common.CheckCallBack;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrappers;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xoa.model.workflow.FlowProcess;
import com.xoa.model.workflow.FlowProcessList;
import com.xoa.service.workflow.flowtype.FlowFormTypeService;
import com.xoa.service.workflow.flowtype.FlowProcessService;
import com.xoa.util.ToJson;
import com.xoa.util.dataSource.ContextHolder;

@Controller
@Scope(value = "prototype")
@RequestMapping("/flowProcess")
public class FlowProcessController {

    @Resource
    private FlowProcessService flowProcessService;

    @Autowired
    private WFEFlowProcess wfeFlowProcess;


    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年5月10日 上午9:49:53
     * 方法介绍:   查询设计流程步骤
     * 参数说明:   @param listType
     * 参数说明:   @param flowId 流程id
     * 参数说明:   @param id 主键id
     * 参数说明:   @param request 请求
     * 参数说明:   @return
     *
     * @return ToJson<FlowProcess>  流程步骤信息
     */
    @ResponseBody
    @RequestMapping(value = "findFlow", produces = {"application/json;charset=UTF-8"})
    public ToJson<FlowProcess> findFlow(
//	    		@RequestParam("listType") String listType, 
//	    		@RequestParam("flowId") int flowId, 
            @RequestParam("id") int id,
            HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        ToJson<FlowProcess> json = new ToJson<FlowProcess>(0, null);
        try {
            FlowProcess flowProcess = flowProcessService.find(id);
            json.setObject(flowProcess);
            json.setMsg("OK");
            json.setFlag(0);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
        }
        return json;

    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年5月10日 上午11:18:20
     * 方法介绍:   修改后保存
     * 参数说明:   @param flowProcess 设计流程实体类
     * 参数说明:   @param request 请求
     * 参数说明:   @return
     *
     * @return ToJson<FlowProcess>
     */
    @ResponseBody
    @RequestMapping(value = "saveFlow", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    public ToJson<FlowProcess> saveFlow(FlowProcess flowProcess,
                                        HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        if (flowProcess.getAutoUserOp() != null && flowProcess.getAutoUserOp().contains(",")) {
            flowProcess.setAutoUserOp(flowProcess.getAutoUserOp().substring(0, flowProcess.getAutoUserOp().length() - 1));
        }
        //如果当前节点为子流程节点，经办人，部门，角色清空
        if(flowProcess.getChildFlow()!=0){
            flowProcess.setPrcsPriv(null);//角色
            flowProcess.setPrcsDept(null);//部门
            flowProcess.setPrcsUser(null);//人员
            flowProcess.setPrcsUserName(null);
            flowProcess.setPrcsDeptName(null);
            flowProcess.setPrcsPrivName(null);
        }

        return flowProcessService.updateByPrimaryKeySelective(flowProcess);
    }


    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年5月19日 下午6:57:03
     * 方法介绍:   新增流程
     * 参数说明:   @param flowProcess
     * 参数说明:   @param request
     * 参数说明:   @return
     * 调优修改
     *
     * @return ToJson<FlowProcess>
     */
    @ResponseBody
    @RequestMapping(value = "insert", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    public ToJson<FlowProcess> insert(FlowProcess flowProcess,
                                      HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return flowProcessService.insertSelective(flowProcess);
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年5月20日 上午10:37:09
     * 方法介绍:   修改
     * 参数说明:   @param id
     * 参数说明:   @param request
     * 参数说明:   @return
     *
     * @return ToJson<FlowProcess>
     */
    @ResponseBody
    @RequestMapping(value = "doedit", produces = {"application/json;charset=UTF-8"})
    public ToJson<FlowProcess> doedit(int id,
                                      HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        ToJson<FlowProcess> json = new ToJson<FlowProcess>(0, null);
        try {
            FlowProcess flowProcess = flowProcessService.find(id);
            json.setObject(flowProcess);
            json.setMsg("OK");
            json.setFlag(0);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
        }
        return json;
    }


    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年5月20日 上午10:37:19
     * 方法介绍:   查询flowid下所有流程
     * 参数说明:   @param flowId 流程id
     * 参数说明:   @param request 请求
     * 参数说明:   @return
     *
     * @return ToJson<FlowProcess> 流程信息
     */
    @ResponseBody
    @RequestMapping(value = "findFlowId", produces = {"application/json;charset=UTF-8"})
    public ToJson<FlowProcess> findFlowId(
            @RequestParam("flowId") int flowId,
            HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        ToJson<FlowProcess> json = new ToJson<FlowProcess>(0, null);
        try {
            List<FlowProcess> list = flowProcessService.findFlowId(flowId);
            json.setObj(list);
            json.setMsg("OK");
            json.setFlag(0);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
     * 创建作者:   张龙飞
     * 创建日期:   2017年5月20日 上午10:37:52
     * 方法介绍:   删除流程
     * 参数说明:   @param id 流程id
     * 参数说明:   @param request 请求
     * 参数说明:   @return
     *
     * @return ToJson<FlowProcess>  返回流程信息
     */
    @ResponseBody
    @RequestMapping(value = "delete", produces = {"application/json;charset=UTF-8"})
    public ToJson<FlowProcess> delete(
            @RequestParam("id") int id,
            HttpServletRequest request) {
       /* Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);*/

        String prcsId = request.getParameter("prcsId");
        String flowId = request.getParameter("flowId");

        return flowProcessService.delete(id, prcsId, flowId);
    }

    /**
     * 创建作者:
     * 创建日期:   2017年5月20日 上午10:38:27
     * 方法介绍:   查询流程
     * 参数说明:   @param flowId
     * 参数说明:   @param request
     * 参数说明:   @return
     *
     * @return ToJson<FlowProcess>
     */
    @ResponseBody
    @RequestMapping(value = "flowview", produces = {"application/json;charset=UTF-8"})
    public ToJson<FlowProcessList> flowview(
            @RequestParam("flowId") Integer flowId,
            @RequestParam(value = "runId", required = false) Integer runId,
            @RequestParam(value = "showType", required = false, defaultValue = "0") Integer showType,
            HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
       /* if (StringUtils.checkNull(userId)) {
            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            userId = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie).getUserId();
        }*/
        return wfeFlowProcess.flowView(flowId, runId);
        //自由流程和固定流程，目前只有固定流程，所以暂时注释掉
        /*if (showType == 0) {
            return wfeFlowProcess.flowView(flowId, runId, userId);
        } else {
            return wfeFlowProcess.myFlowView(flowId, runId, userId);
        }*/
//			if(runId!=null){
//				// 我经办的步骤
//				return flowProcessService.myFlowView(flowId,runId,userId);
//			}else{
//				return flowProcessService.flowView(flowId);
//			}
    }


    /**
     * 创建作者:   张勇
     * 创建日期:   2017/6/3 11:24
     * 方法介绍:   修改流程节点坐标
     * 参数说明:   @return
     *
     * @return ToJson<FlowProcess>
     */

    @RequestMapping(value = "updateTopAndLeft", produces = {"application/json;charset=UTF-8"})
    public @ResponseBody
    ToJson<FlowProcess> updateTopAndLeft(
            FlowProcess flowProcess,
            HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return flowProcessService.updateTopAndLeft(flowProcess);
    }

    /**
     * 创建作者:   张勇
     * 创建日期:   2017/6/8 17:52
     * 方法介绍:   连接线删除
     * 参数说明:
     *
     * @return
     */
    @RequestMapping(value = "deleteTopAndLeft", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public @ResponseBody
    ToJson<FlowProcess> deleteTopAndLeft(
            FlowProcess flowProcess,
            @RequestParam("toPrcsLine") String toPrcsLine,
            HttpServletRequest request) {
       /* Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);*/
        return flowProcessService.findPrcessLine(flowProcess, toPrcsLine);
    }

    @RequestMapping(value = "xs", produces = {"application/json;charset=UTF-8"})
    public String xs() {
        return "app/workflow/flowprocess/flowProcess";
    }

    /**
     * name:获取流程附件信息
     * url:/flowProcess/getFlowAttachment
     *
     * @param request
     * @param runId   工作id
     * @return
     */
    @RequestMapping("/getFlowAttachment")
    @ResponseBody
    public ToJson getFlowAttachment(HttpServletRequest request, Integer runId) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        String company = "xoa" + loginDateSouse;
        if (StringUtils.checkNull(loginDateSouse)) {
            company = "xoa1001";
        }
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return flowProcessService.getFlowAttachment(runId, company,user);
    }

    /**
     * name:获取流程会签信息
     * url:/flowProcess/getFlowFeedBack
     *
     * @param runId
     * @return
     */
    @RequestMapping("/getFlowFeedBack")
    @ResponseBody
    public ToJson getFlowFeedBack(String runId, HttpServletRequest request) {
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        return flowProcessService.selectFlowFeedBackByRunId(runId, user.getUserId());
    }

    @RequestMapping(value = "getFlowRunPrecsAll", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public BaseWrappers getFlowRunPrecsAll(String runId) {
        return wfeFlowProcess.getFlowRunPrecsAll(runId);
    }

    /**
     * 为所有会签意见区分主办人与经办人所签
     * 王禹萌
     * 2018-08-08 16：43
     *
     * @param runId 流水号
     * @return
     */
    @RequestMapping(value = "getFlowRunPrecsOpFlag", produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public BaseWrappers getFlowRunPrecsOpFlag(String runId) {
        return wfeFlowProcess.getFlowRunPrecsOpFlag(runId);
    }


    @RequestMapping(value = "/getSonFlow")
    @ResponseBody
    public ToJson getSonFlow(Integer flowId, Integer prcsId) {
        return flowProcessService.getSonFlow(flowId, prcsId);
    }


}
